<!-- 部门管理 部门列表组件 -->
<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <!-- <el-breadcrumb-item><a>用户管理</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>正常日志</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="正常日志" name="first">
          <el-form
            :model="queryInfo"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="关键字" prop="keyWord">
              <el-input
                v-model="queryInfo.keyWord"
                placeholder="请输入关键字名字"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleQuery"
                type="primary"
                icon="el-icon-search"
                size="mini"
                >搜索</el-button
              >
              <el-button @click="resetQuery" icon="el-icon-refresh" size="mini"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <el-table :data="userList" tooltip-effect="dark" style="width: 100%">
            <el-table-column prop="title" label="名称">
            </el-table-column>
            <el-table-column prop="requestIp" label="IP地址"> </el-table-column>
            <el-table-column prop="requestPosition" label="地址">
            </el-table-column>
            <el-table-column prop="operationMethod" label="方法名称">
            </el-table-column>
            <el-table-column prop="operationClass" label="类名称">
            </el-table-column>
            <el-table-column prop="operationUser" label="用户">
            </el-table-column>
            <el-table-column prop="operationTime" label="操作时间">
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="220"
              class-name="small-padding fixed-width"
            >
              <template v-if="scope.row.userId !== 1" slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="updateTaskHandle(scope.row)"
                  >详情</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="异常日志" name="second">
          <el-form
            :model="queryUnusual"
            ref="queForm"
            size="small"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="关键字" prop="keyWord">
              <el-input
                v-model="queryUnusual.keyWord"
                placeholder="请输入关键字名字"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button
                @click="handleQue"
                type="primary"
                icon="el-icon-search"
                size="mini"
                >搜索</el-button
              >
              <el-button @click="reset" icon="el-icon-refresh" size="mini"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
            :data="unOperation"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="title" label="名称">
            </el-table-column>
            <el-table-column prop="requestIp" label="IP地址"> </el-table-column>
            <el-table-column prop="requestPosition" label="地址">
            </el-table-column>
            <el-table-column prop="operationMethod" label="方法名称">
            </el-table-column>
            <el-table-column prop="operationClass" label="类名称">
            </el-table-column>
            <el-table-column prop="operationUser" label="用户">
            </el-table-column>
            <el-table-column prop="operationTime" label="操作时间">
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="220"
              class-name="small-padding fixed-width"
            >
              <template v-if="scope.row.userId !== 1" slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="updateTaskHandle(scope.row)"
                  >详情</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSize"
            @current-change="handleCurrent"
            :current-page="queryUnusual.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="queryUnusual.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="toatls"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer
      title="详情"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-descriptions
        style="padding:0 20px 0 20px;"
        title=""
        direction="horizontal"
        :column="1"
        border
      >
        <el-descriptions-item label="名称" prop="requestParam">{{
          this.detailData.title
        }}</el-descriptions-item>
        <el-descriptions-item label="请求IP">{{
          this.detailData.requestIp
        }}</el-descriptions-item>
        <el-descriptions-item label="IP来源" :span="2">{{
          this.detailData.requestUri
        }}</el-descriptions-item>
        <el-descriptions-item label="请求地址">{{
          this.detailData.requestPosition
        }}</el-descriptions-item>
        <el-descriptions-item label="操作类">{{
          this.detailData.operationClass
        }}</el-descriptions-item>
        <el-descriptions-item label="操作方法">{{
          this.detailData.operationMethod
        }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{
          this.detailData.operationTime
        }}</el-descriptions-item>
        <el-descriptions-item label="操作人">{{
          this.detailData.operationUser
        }}</el-descriptions-item>
      </el-descriptions>
      <!-- {{ this.reqStyle }} -->
      <div class="topStyle">
        <span class="titleStyle">请求参数:</span>
        <span>
          <pre><code class="language-css" id="html_code">{{ this.reqStyle }}</code></pre>
        </span>
      </div>
      <div class="botStyle">
        <span class="titleStyle">返回结果:</span>
        <pre><code class="language-css" id="html_code_two">{{ this.resStyle }}</code></pre>
        <!-- <div class="contentStyle"><span style="color: #ccc;">{{ this.detailData.responseParam }}</span></div> -->
      </div>
      <a href="" style="display:none">{{ this.a }}</a>
    </el-drawer>
  </div>
</template>

<script>
import Hljs from 'highlight.js'
import 'highlight.js/styles/stackoverflow-light.css'
export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      // watch_data:[
      //     {
      //       date:'2022-10-1 10:12;10',
      //       message:{
      //         filter:{
      //           filter_name:'abcdefg',
      //           status:'expected'
      //         }
      //       }
      //     }
      // ],
      drawer: false,
      a: '隐藏',
      detailData: {},
      direction: 'rtl',
      userList: [],
      unOperation: [],
      total: 0,
      toatls: 0,
      reqStyle: null,
      resStyle: null,
      activeName: 'first',
      queryInfo: {
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        keyWord: undefined, //关键字
        status: undefined // 操作结果 success：成功、fail：失败
      },
      queryUnusual: {
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        keyWord: undefined, // 关键字
        status: undefined // 操作结果 success：成功、fail：失败
      },
      code: {}
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {
    this.getOperationLogList('success')
  },
  methods: {
    // -------------------------正常操作-------------------------------------
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getOperationLogList('success')
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getOperationLogList('success')
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryInfo.currentPage = 1
      this.getOperationLogList('success')
    },
    // 重置按钮操作
    resetQuery() {
      //  this指向$refs的是通过ref获得的实例对象loginFormRef
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },

    //  --------------------------异常操作-----------------------------------
    // 搜索按钮操作
    handleQue() {
      this.queryUnusual.currentPage = 1
      this.getOperationLogList('fail')
    },
    // 重置按钮操作
    reset() {
      //this指向$refs的是通过ref获得的实例对象loginFormRef
      this.$refs.queForm.resetFields()
      this.handleQue()
    },
    handleSize(newSize) {
      this.queryUnusual.pageSize = newSize
      this.getOperationLogList('fail')
    },
    handleCurrent(newPage) {
      this.queryUnusual.currentPage = newPage
      this.getOperationLogList('fail')
    },

    // tabs 切换的方法
    handleClick(tab, event) {
      if (tab.index === '0') {
        this.getOperationLogList('success')
      } else {
        this.getOperationLogList('fail')
      }
    },

    async getOperationLogList(state) {
      this.queryInfo.status = state
      this.queryUnusual.status = state
      const { data: res } = await this.$http.post(
        '/sys-job-log/page',
        state == 'success' ? this.queryInfo : this.queryUnusual
      )
      if (res.code === 20000) {
        this.userList = res.data.records
        this.unOperation = res.data.records
        this.total = parseInt(res.data.total)
        this.toatls = parseInt(res.data.total)
      }
    },

    // 详情
    updateTaskHandle(row) {
      this.drawer = true
      this.detailData = row
      this.reqStyle = this.format(row.requestParam, false)
      if (typeof row.responseParam == 'string') {
        try {
          var obj = JSON.parse(row.responseParam);
          if (typeof obj == 'object' && obj) {
            this.resStyle = this.format(row.responseParam, false)
            return true;
          } else {
            this.resStyle = row.responseParam
            return false;
          }
        } catch (e) {
          this.resStyle = row.responseParam
          return false;
        }
      }
      // // 延迟函数
      // clearTimeout(this.timer);  //清除延迟执行
      // this.timer = setTimeout(() => { //设置延迟执行
      //   Hljs.highlightBlock(document.querySelector('#html_code'))
      //   Hljs.highlightBlock(document.querySelector('#html_code_two'))
      // }, 100);
    },

    // 详情关闭
    handleClose(done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
          done()
        // })
        // .catch(_ => {})
    },

    format(txt, compress /*是否为压缩模式*/) {
      /* 格式化JSON源码(对象转换为JSON文本) */
      var indentChar = '    '
      if (/^\s*$/.test(txt)) {
        alert('数据为空,无法格式化! ')
        return
      }
      try {
        var data = eval('(' + txt + ')')
      } catch (e) {
        // alert('数据源语法错误,格式化失败! 错误信息: ' + e.description, 'err')
        console.log('数据源语法错误,格式化失败! 错误信息: ' + e.description, 'err')
        return
      }
      var draw = [],
        last = false,
        This = this,
        line = compress ? '' : '\n',
        nodeCount = 0,
        maxDepth = 0

      var notify = function(name, value, isLast, indent /*缩进*/, formObj) {
        nodeCount++ /*节点计数*/
        for (var i = 0, tab = ''; i < indent; i++)
          tab += indentChar /* 缩进HTML */
        tab = compress ? '' : tab /*压缩模式忽略缩进*/
        maxDepth = ++indent /*缩进递增并记录*/
        if (value && value.constructor == Array) {
          /*处理数组*/
          draw.push(
            tab + (formObj ? '"' + name + '":' : '') + '[' + line
          ) /*缩进'[' 然后换行*/
          for (var i = 0; i < value.length; i++)
            notify(i, value[i], i == value.length - 1, indent, false)
          draw.push(
            tab + ']' + (isLast ? line : ',' + line)
          ) /*缩进']'换行,若非尾元素则添加逗号*/
        } else if (value && typeof value == 'object') {
          /*处理对象*/
          draw.push(
            tab + (formObj ? '"' + name + '":' : '') + '{' + line
          ) /*缩进'{' 然后换行*/
          var len = 0,
            i = 0
          for (var key in value) len++
          for (var key in value)
            notify(key, value[key], ++i == len, indent, true)
          draw.push(
            tab + '}' + (isLast ? line : ',' + line)
          ) /*缩进'}'换行,若非尾元素则添加逗号*/
        } else {
          if (typeof value == 'string') value = '"' + value + '"'
          draw.push(
            tab +
              (formObj ? '"' + name + '":' : '') +
              value +
              (isLast ? '' : ',') +
              line
          )
        }
      }
      var isLast = true,
        indent = 0
      notify('', data, isLast, indent, false)
      return draw.join('')
    }
  },
  mounted() {}
  // 组件方法
}
</script>

<style scoped lang="less">
// 表格样式
.el-table {
  margin-top: 15px;
  font-size: 12px;
}

.topStyle {
  margin: 20px 0 20px 20px;
}

.botStyle {
  margin-left: 20px;
}

.titleStyle {
  display: block;
}

.contentStyle {
  border-radius: 10px;
  margin-top: 20px;
  width: 500px;
  // height: 100px;
  padding: 10px;
  background-color: black;
  overflow-x: auto;
  overflow-y: auto;
}
</style>
